#include "PhysicsManager.h"

#define M_PI 3.14f
#define RADTODEG 57.295779513082320876f

PhysicsManager::PhysicsManager()
{
}

PhysicsManager::~PhysicsManager()
{
	if(gameWorld) delete gameWorld;
	gameWorld = 0;
}

void PhysicsManager::setupWorld(b2Vec2 gravity)
{
	gameWorld = new b2World(gravity);
	gameWorld->SetAllowSleeping(true);
}

void PhysicsManager::updateGameWorld(std::vector<RectEntity*> activeRectList, std::vector<CircleEntity*> activeCircleList, float32 timeStep)
{   
	int32 velocityIterations = 2;
	int32 positionIterations = 2;
	gameWorld->Step(timeStep, velocityIterations, positionIterations);
	applyRectChanges(activeRectList);
	applyCircleChanges(activeCircleList);
}

void PhysicsManager::applyRectChanges(std::vector<RectEntity*> activeRectList)
{
	//#pragma loop(hint_parallel(8))
	for(int i = 0; i < activeRectList.size(); i++)
	{
		b2Vec2 position = activeRectList.at(i)->rectBody->GetPosition();
		activeRectList.at(i)->rectShape.setPosition(position.x, -position.y);

		float angle = activeRectList.at(i)->rectBody->GetAngle();
		if(activeRectList.at(i)->rectBody->GetContactList())
		activeRectList.at(i)->rectShape.setRotation(-angle * RADTODEG);
	}
}

void PhysicsManager::applyCircleChanges(std::vector<CircleEntity*> activeCircleList)
{
	for(int i = 0; i < activeCircleList.size(); i++)
	{
		b2Vec2 position = activeCircleList.at(i)->circleBody->GetPosition();
		activeCircleList.at(i)->circleShape.setPosition(position.x, -position.y);

		float angle = activeCircleList.at(i)->circleBody->GetAngle();
		activeCircleList.at(i)->circleShape.setRotation(-angle * RADTODEG);
	}
}

b2World *PhysicsManager::getGameWorld()
{
	return gameWorld;
}